package com.winit.cloudlink.mgmt.config;

import com.winit.cloudlink.Cloudlink;
import com.winit.cloudlink.config.Metadata;
import com.winit.cloudlink.config.MqServerOptions;
import org.springframework.amqp.rabbit.connection.CachingConnectionFactory;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class RabbitAutoConfigure {

    @Autowired
    private Cloudlink cloudlink;

    @Bean
    public ConnectionFactory connectionFactory() {
        Metadata metadata = cloudlink.getMetadata();
        MqServerOptions serverOptions = metadata.getCurrentZone().getMqServerOptions();
        CachingConnectionFactory rabbitConnectionFactory = new CachingConnectionFactory(serverOptions.getHost(),
                serverOptions.getPort());
        rabbitConnectionFactory.setVirtualHost(serverOptions.getVirtualHost());
        rabbitConnectionFactory.setUsername(serverOptions.getUsername());
        rabbitConnectionFactory.setPassword(serverOptions.getPassword());
        rabbitConnectionFactory.setPublisherReturns(true);
        rabbitConnectionFactory.setPublisherConfirms(false);
        return rabbitConnectionFactory;
    }
}
